package com.rj.framework.validation;

import com.rj.framework.context.Context;
import jakarta.validation.ConstraintValidator;
import jakarta.validation.ConstraintValidatorFactory;
import jakarta.validation.ValidationException;

import java.util.HashMap;
import java.util.Map;

/**
 * 自定义ConstraintValidatorFactory，用于创建带有上下文参数的ConstraintValidator实例
 */
public class ContextAwareConstraintValidatorFactory implements ConstraintValidatorFactory {

    private final Context context;
    private final Map<Class<?>, ConstraintValidator<?, ?>> validatorCache = new HashMap<>();

    public ContextAwareConstraintValidatorFactory(Context context) {
        this.context = context;
    }

    @Override
    public <T extends ConstraintValidator<?, ?>> T getInstance(Class<T> key) {
        // 从缓存中获取
        ConstraintValidator<?, ?> instance = validatorCache.get(key);
        if (instance == null) {
            // 创建新实例并注入上下文
            instance = createInstance(key);
            validatorCache.put(key, instance);
        }
        T result = (T) instance;
        return result;
    }

    private <T extends ConstraintValidator<?, ?>> T createInstance(Class<T> key) {
        try {
            T instance = key.getDeclaredConstructor().newInstance();
            // 注入上下文（如果支持）
            if (instance instanceof ContextAwareValidator) {
                ContextAwareValidator contextAware = (ContextAwareValidator) instance;
                contextAware.setContext(context);
            }

            return instance;
        } catch (Exception e) {
            throw new ValidationException("Failed to create constraint validator: " + key, e);
        }
    }

    @Override
    public void releaseInstance(ConstraintValidator<?, ?> instance) {
        // 不释放实例，保持缓存
    }
}